package com.hxgis.statisticanalysis.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.List;

/**
 * 导出文档工具类
 */
public class ExportUtil {
    public static final String CT_SYM_CHECK = "F0" + Integer.toHexString(254);
    public static final String CT_SYM_UNCHECK = "F0" + Integer.toHexString(168);

    public static final String CHECK = "☑";
    public static final String UNCHECK = "☐";

    /**
     * 设置当前行背景色
     *
     * @param row       行
     * @param cellColor
     */
    public static void setCellBackgroundColor(XWPFTableRow row, String cellColor) {
        if (StringUtils.isEmpty(cellColor)) {
            return;
        }
        //最后一列不上色
        List<XWPFTableCell> tableCells = row.getTableCells();
        for (int i = 0; i < tableCells.size() - 1; i++) {
            XWPFTableCell cell = tableCells.get(i);
            cell.setColor(cellColor);
        }
    }

    /**
     * 跨列合并单元格
     *
     * @param table
     * @param row
     * @param fromCell
     * @param toCell
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if (cellIndex == fromCell) {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 跨行合并单元格
     *
     * @param table
     * @param col
     * @param fromRow
     * @param toRow
     */
    public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == fromRow) {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * @Description: 设置列宽和垂直对齐方式
     */
    public static void setCellWidthAndVAlign(XWPFTableCell cell, String width, STVerticalJc.Enum typeEnum, STJc.Enum vAlign) {
        CTTc cttc = cell.getCTTc();
        CTTcPr cellPr = cttc.addNewTcPr();
        cellPr.addNewVAlign().setVal(typeEnum);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(vAlign);
        CTTblWidth tblWidth = cellPr.isSetTcW() ? cellPr.getTcW() : cellPr.addNewTcW();
        if (!StringUtils.isEmpty(width)) {
            tblWidth.setW(new BigInteger(width));
            tblWidth.setType(STTblWidth.DXA);
        }
    }

    /**
     * 判断是否是整数
     *
     * @param str
     * @return boolean
     */
    public static boolean isNumeric(String str) {
        if (str.indexOf(".") > 0) {
            return false;
        }
        return true;
    }

    /**
     * 设置单元格内容
     *
     * @param cell  单元格
     * @param value 文本内容
     */
    public static void setCellValue(XWPFTableCell cell, String value) {
        setCellValue(cell, value, null);
    }

    public static void setCellValue(XWPFTableCell cell, String value, Integer fontSize) {
        if (fontSize == null) {
            fontSize = 10;
        }
        setCellValue(cell, value, fontSize, false, null, null, null, null);
    }

    /**
     * @param cell      单元格
     * @param value     文本内容
     * @param fontSize  文本字体大小
     * @param isBold    是否粗体
     * @param font      文本字体
     * @param textColor 文本颜色
     */
    public static void setCellValue(XWPFTableCell cell, String value, Integer fontSize, boolean isBold, String font, String textColor) {
        setCellValue(cell, value, fontSize, isBold, font, textColor, null, null);

    }

    /**
     * @param cell      单元格
     * @param value     文本内容
     * @param fontSize  文本字体大小
     * @param isBold    是否粗体
     * @param font      文本字体
     * @param textColor 文本颜色
     * @param vAlign    竖向排列方式
     * @param align     横向排列方式
     */
    public static void setCellValue(XWPFTableCell cell, String value, Integer fontSize, Boolean isBold, String font,
                                    String textColor, XWPFTableCell.XWPFVertAlign vAlign, ParagraphAlignment align) {
        XWPFParagraph cellParagraph = cell.getParagraphs().get(0);
        XWPFRun cellParagraphRun = cellParagraph.createRun();

        if (value != null && value.contains("\r")) {
            String[] text = value.split("\r");
            for (int k = 0; k < text.length; k++) {
                if (k != 0) {
                    cellParagraphRun.addBreak(BreakType.TEXT_WRAPPING);
                }
                cellParagraphRun.setText(text[k]);
            }
        } else {
            cellParagraphRun.setText(value);
        }
        if (fontSize != null && fontSize > 0) {
            cellParagraphRun.setFontSize((short) fontSize.intValue());
        }
        if (isBold != null && isBold) {
            cellParagraphRun.setBold(true);
        }
        if (!StringUtils.isEmpty(font)) {
            cellParagraphRun.setFontFamily(font);
        }
        if (!StringUtils.isEmpty(textColor)) {
            cellParagraphRun.setColor(textColor);
        }
        if (vAlign != null) {
            cell.setVerticalAlignment(vAlign);
        } else {
            cell.setVerticalAlignment(v_align);
        }
        if (align != null) {
            cellParagraph.setAlignment(align);
        } else {
            cellParagraph.setAlignment(h_align);
        }

    }


    private static final XWPFTableCell.XWPFVertAlign v_align = XWPFTableCell.XWPFVertAlign.CENTER;
    private static final ParagraphAlignment h_align = ParagraphAlignment.CENTER;

    /**
     * 为段落添加符号
     *
     * @param cell    单元格
     * @param charStr 指定符号的charStr
     */
    public static void setCellCTSym(XWPFTableCell cell, String charStr) {
        XWPFParagraph cellParagraph = cell.getParagraphs().get(0);
        XWPFRun run = cellParagraph.createRun();
        List<CTSym> symList = run.getCTR().getSymList();
        symList.add(getCTSym("Wingdings", charStr));

    }

    /**
     * 复制行
     *
     * @param target
     * @param source
     */
    public static void copyTableRow(XWPFTableRow target, XWPFTableRow source) {
        // 复制样式
        if (source.getCtRow() != null) {
            target.getCtRow().setTrPr(source.getCtRow().getTrPr());
        }
        // 复制单元格
        for (int i = 0; i < source.getTableCells().size(); i++) {
            XWPFTableCell cell1 = target.getCell(i);
            XWPFTableCell cell2 = source.getCell(i);
            if (cell1 == null) {
                cell1 = target.addNewTableCell();
            }
            copyTableCell(cell1, cell2);
        }
    }

    /**
     * 复制单元格
     *
     * @param target
     * @param source
     */
    public static void copyTableCell(XWPFTableCell target, XWPFTableCell source) {
        // 列属性
        if (source.getCTTc() != null) {
            target.getCTTc().setTcPr(source.getCTTc().getTcPr());
        }
        // 删除段落
        for (int pos = 0; pos < target.getParagraphs().size(); pos++) {
            target.removeParagraph(pos);
        }
        // 添加段落
        for (XWPFParagraph sp : source.getParagraphs()) {
            XWPFParagraph targetP = target.addParagraph();
            copyParagraph(targetP, sp);
        }
    }

    /**
     * 复制段落
     *
     * @param target
     * @param source
     */
    public static void copyParagraph(XWPFParagraph target, XWPFParagraph source) {
        // 设置段落样式
        target.getCTP().setPPr(source.getCTP().getPPr());
        // 移除所有的run
        for (int pos = target.getRuns().size() - 1; pos >= 0; pos--) {
            target.removeRun(pos);
        }
        // copy 新的run
        for (XWPFRun s : source.getRuns()) {
            XWPFRun targetrun = target.createRun();
            copyRun(targetrun, s);
        }

    }

    /**
     * 复制run
     *
     * @param target
     * @param source
     */
    public static void copyRun(XWPFRun target, XWPFRun source) {
        // 设置run属性
        target.getCTR().setRPr(source.getCTR().getRPr());
        // 设置文本
        target.setText(source.text());

    }

    /**
     * 清理行内容
     *
     * @param row
     */
    public static void clearRow(XWPFTableRow row) {
        List<XWPFTableCell> cells = row.getTableCells();
        for (XWPFTableCell cell : cells) {
            List<XWPFParagraph> paragraphs = cell.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                for (int i = 0; i < paragraph.getRuns().size(); i++) {
                    paragraph.removeRun(i);
                }
            }
        }
    }

    public static void exportDoc(HttpServletResponse response, XWPFDocument doc, String fileName) throws IOException {
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setContentType("application/vnd.ms-word");
        response.setHeader("Content-disposition", "attachment; filename=" +
                new String(fileName.getBytes("gbk"), "iso8859-1") + ".docx");
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        doc.write(output);
        output.close();
    }

    public static void exportExcel(HttpServletResponse response, XSSFWorkbook wb, String fileName) throws IOException {
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=" +
                new String(fileName.getBytes("gbk"), "iso8859-1") + ".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        wb.write(output);
        output.close();
    }

    public static void exportExcel(HttpServletResponse response, HSSFWorkbook wb, String fileName) throws IOException {
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=" +
                new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }

    /**
     * 获取指定字符
     *
     * @param wingType
     * @param charStr
     * @return
     * @throws Exception
     */
    public static CTSym getCTSym(String wingType, String charStr) {
        CTSym sym = null;
        try {
            sym = CTSym.Factory.parse("<xml-fragment w:font=\""
                    + wingType + "\" w:char=\"" + charStr
                    + "\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\"> </xml-fragment>");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sym;
    }

}
